package com.heima.wemedia.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.utils.common.constatus.WemediaConstants;
import com.heima.wemedia.mapper.WemetiaMapper;
import com.heima.wemedia.mapper.WmNewSMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewSMapper, WmNews> implements WmNewsService {
    @Autowired
    private  WemetiaMapper mapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult getWmNewsList(WmNewsPageReqDto wmNewsPageReqDto) {
        IPage<WmNews> page=new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        if (wmNewsPageReqDto==null)
        {
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数不合法");
        }
            wmNewsPageReqDto.checkParam();
            if (null==WmThreadLocalUtil.getUser())
            {
                return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请返回登陆");
            }
            if(wmNewsPageReqDto.getStatus()!=null)
            {
                wmNewsLambdaQueryWrapper.eq(WmNews::getStatus,wmNewsPageReqDto.getStatus());
            }
        //频道精确查询
        if(wmNewsPageReqDto.getChannelId() != null){
            wmNewsLambdaQueryWrapper.eq(WmNews::getChannelId,wmNewsPageReqDto.getChannelId());
        }

        //时间范围查询
        if(wmNewsPageReqDto.getBeginPubDate()!=null && wmNewsPageReqDto.getEndPubDate()!=null){
            wmNewsLambdaQueryWrapper.between(WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate());
        }

        //关键字模糊查询
        if(StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())){
            wmNewsLambdaQueryWrapper.like(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }
        wmNewsLambdaQueryWrapper.eq(WmNews::getUserId,WmThreadLocalUtil.getUser().getId());

         page = page(page, wmNewsLambdaQueryWrapper);
        ResponseResult responseResult=new PageResponseResult(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize()
        ,(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }
@Autowired
private WmNewsAutoScanService wmNewsAutoScanService;
    @Override
    public ResponseResult submitNew(WmNewsDto dto) {
        //判断参数是否适合
        if (dto==null)
        {
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无效参数");
        }
        WmNews wmNews=new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //赋值图片内容
        if(dto.getImages()!=null&&dto.getImages().size()>0)
        {
            wmNews.setImages(org.apache.commons.lang.StringUtils.join(dto.getImages(),","));
        }
        //如果当前封面类型为自动 -1
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        //2.判断是否为草稿  如果为草稿结束当前方法
        if(dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<String> materials =  ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials,wmNews.getId());

        wmNewsAutoScanService.authActicle(wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    //文章上下架功能
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto.getId()==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"缺少id参数");
        }
        WmNews byId = getById(dto.getId());
        //判断文章是否存在
        if (byId==null)
        {
            return  ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"文章已经不存在");
        }
        //判断文章是否已经发布
        short code = WmNews.Status.PUBLISHED.getCode();
        if(!byId.getStatus().equals(code))
        {
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章未发布");
        }
        //修改文章enable
        if (dto.getEnable()!=null&& dto.getEnable() > -1 && dto.getEnable() < 2)
        {
            update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,dto.getId()));
        }
      return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        saveRelativeInfo(materials,id,WemediaConstants.WM_CONTENT_REFERENCE);

    }

    private void saveRelativeInfo(List<String> materials, Integer id, Short wmContentReference) {

        if(materials!=null && !materials.isEmpty()){
            //通过图片的url查询素材的id
            List<WmMaterial> dbMaterials = mapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                            .in(WmMaterial::getUrl, materials));
            //判断素材是否存在
            if (dbMaterials==null&&dbMaterials.size()==0)
            {
                throw  new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            if(materials.size() != dbMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            List<Integer> collect = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
          wmNewsMaterialMapper.saveRelations(collect,id,wmContentReference);

        }



    }

    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }
        return materials;
    }

    //保存或者修改文章
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);//默认上架
        if(wmNews.getId()==null)
        {
            save(wmNews);
        }
        //修改操作先删除，再添加
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        remove(wmNewsLambdaQueryWrapper.eq(WmNews::getId,wmNews.getId()));
        save(wmNews);
    }
}
